<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(search, index) in searchList"
      :key="index"
      @click="$emit('searchs', search)"
      icon="search"
    >
      <template #title>
        <div v-html="htmlStr(search, searchText)"></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { searchData } from '@/api/search'
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  components: {},
  filters: {},
  watch: {
    searchText: {
      immediate: true,
      handler(q) {
        // 防抖处理
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.searchdemo(q)
        }, 500)
      }
    }
  },
  data() {
    return {
      searchList: [],
      timer: null
    }
  },
  computed: {
    // 关键字高亮
    htmlStr() {
      return (str, searchText) => {
        return str.replaceAll(
          searchText,
          `<span style="color:red">${searchText}</span>`
        )
      }
    }
  },
  beforeDestroy() {
    clearTimeout(this.timer)
  },
  created() {},
  mounted() {},
  methods: {
    // 获取搜索建议数据
    async searchdemo(q) {
      try {
        const { data } = await searchData(q)
        this.searchList = data.options
        console.log(this.searchList)
      } catch (error) {
        this.$toast('数据获取失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
